import wx from 'weixin-js-sdk'

// 检查微信环境
export function checkWechatEnv(callback) {
  var ua = window.navigator.userAgent.toLowerCase()
  if (ua.match(/MicroMessenger/i) && ua.match(/MicroMessenger/i).toString() === 'micromessenger') { // 判断是否是微信环境
    // 微信环境
    wx.miniProgram.getEnv(function (res) {
      if (res.miniprogram) {
        // 小程序环境下
        callback('miniprogram')
      } else {
        // 非小程序环境
        callback('wechat')
      }
    })
  } else {
    // 非微信环境
    callback('outOfWechat')
  }
}

// 解析URL查询参数
export function parseQueryString() {
  const query = {}
  const search = window.location.search

  if (search.indexOf('?') === 0) {
    const parameters = search.slice(1).split('&')
    for (let i = 0; i < parameters.length; i++) {
      const p = parameters[i]
      const kv = p.split('=')
      if (kv.length === 2) {
        const k = kv[0]
        const v = kv[1]
        if (k) {
          query[k] = decodeURIComponent(v)
        }
      }
    }
  }

  return query
};

// 拼接URL查询参数
export const joinQueryString = (query) => {
  let search = '?'

  for (const key in query) {
    let value = query[key]
    if (typeof (value) === 'undefined') {
      value = ''
    }
    value = encodeURIComponent(value)
    search += key + '=' + value + '&'
  }
  if (search[search.length - 1] === '&') {
    search = search.substring(0, search.length - 1)
  }

  return search
}


// 官网金钱格式化
export const formatMoney = (number) => {
  let beforePoint = '',
    afterPoint = '',
    newArr = [],
    beforeNumber = '';

  let intnumber = +number;

  let text = parseFloat(intnumber);

  if (text < 0) {
    beforeNumber = '-';
    text = Math.abs(text);
  }

  text += '';

  if (text.indexOf('.') != -1) {
    text = parseFloat(text).toFixed(3) + '';
    text = text.substring(0, text.lastIndexOf('.') + 3);
    let arr = text.split('.');
    beforePoint = arr[0];
    afterPoint = arr[1] == '00' ? '' : ('.' + arr[1]);
  } else {
    beforePoint = text;
  }

  let specialArr = beforePoint.split('');
  specialArr.reverse();
  let len = specialArr.length;

  for (let i = 1; i <= len; i++) {
    newArr.push(specialArr[i - 1]);
    if (i % 3 == 0 && i != len) {
      newArr.push(',');
    }
  }
  beforePoint = [...newArr].reverse();
  beforePoint = beforePoint.join('');
  return beforeNumber + beforePoint + afterPoint;
};